package com.wva.servletcontext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/demo01ServletContext")
public class Demo01ServletContext extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        /**
         * 1.ServletContext对象获取：
         *  1. 通过request对象获取:  request.getServletContext();
         *  2. 通过HttpServlet获取:  this.getServletContext();
         */
        //1. 通过request对象获取
        ServletContext context1 = request.getServletContext();
        //2. 通过HttpServlet获取
        ServletContext context2 = this.getServletContext();
        System.out.println(context1 == context2);//true 是同一个对象


        /**
         * 2.获取MIME类型
         *  String getMimeType(String file)
         */
        String filename = "a.jpg";//image/jpeg
        //4.获取MIME类型
        String mimeType = context1.getMimeType(filename);
        System.out.println(mimeType); //image/jpeg

        /**
         *
         * 3. 域对象：共享数据
         *  setAttribute(String name,Object value) //设置数据
         *  getAttribute(String name)  //获取数据
         *  removeAttribute(String name)  //删除数据
         *
         *  域对象范围：所有用户所有请求的数据
         */
        //设置数据
        context1.setAttribute("msg","haha");


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
